package com.authine.cloudpivot.ext.controller.PersonnFileCheck;

        import cn.hutool.core.lang.Assert;
        import com.authine.cloudpivot.engine.api.model.organization.UserModel;
        import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
        import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
        import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
        import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
        import com.authine.cloudpivot.ext.Utils.CustomSchemaCode;
        import com.authine.cloudpivot.ext.service.CloudSqlService;
        import com.authine.cloudpivot.web.api.config.EducationEnum;
        import com.authine.cloudpivot.web.api.config.FirstEducationEnum;
        import com.authine.cloudpivot.web.api.controller.base.BaseController;
        import lombok.extern.slf4j.Slf4j;
        import org.apache.commons.collections4.MapUtils;
        import org.apache.commons.lang3.StringUtils;
        import org.apache.commons.lang3.time.DateFormatUtils;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.web.bind.annotation.RequestMapping;
        import org.springframework.web.bind.annotation.RestController;

        import java.time.LocalDateTime;
        import java.time.format.DateTimeFormatter;
        import java.util.*;

/**
 *  人事档案点检汇总表
 **/
@RestController
@RequestMapping("/public/PersonnFileCheck")
@Slf4j
public class PersonnFileCheck extends BaseController {


    @Autowired
    CloudSqlService sqlService;

    /**
     *  错失标准  审批流完成后 数据写到-错失标准 基础表 基础
     */
    @RequestMapping("finish")
    public void finish(String bizId){
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.PersonnFileCheck, bizId);

        List<Map<String,Object>> list = (List<Map<String, Object>>) bizObject.get("PersonelFileCheckSubtab");

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        //获取审批人

        String approval = "";

        for (Map<String, Object> map : list) {

            try {
                //获取数据
                Map<String, Object> data = fileInfoBaseMap(map, now, approval);
                //判断是否已存在
                String id = existsBizObject(map);
                if (StringUtils.isNotEmpty(id)) {
                    data.put("id", id);
                }

                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.PersonFileCheckBase, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                log.info("基础表-人员信息基础作成功 ");
                //调用存储过程
                callProcess(id);

            } catch (Exception e) {
                String personNumberHidden = (String) map.get("personNumberHidden");
                String companyNumber = (String) map.get("companyNumber");

                log.info("基础表-人员信息基础操作失败 personNumberHidden={},companyNumber={}", personNumberHidden,companyNumber);
                log.info(e.getMessage(), e);
            }

        }
    }




    /**
     *  调用存储过程
     create   proc    SyncHrArchCheck

     @Companyid   nvarchar(100),   ----公司FID
     @Orgid    nvarchar(100),   ----基层组织FID
     @Poscode   nvarchar(100),   ----岗位代码
     @PersonCode   nvarchar(100),   ----人员代码
     @S01    NVARCHAR(10),   ---- yes   √    no  ×   blank /
     @S02    NVARCHAR(10),
     @S03    NVARCHAR(10),
     @S04    NVARCHAR(10),
     @S05    NVARCHAR(10),
     @S06    NVARCHAR(10),
     @S07    NVARCHAR(10),
     @S08    NVARCHAR(10),
     @S09    NVARCHAR(10),
     @S10    NVARCHAR(10),
     @S14    NVARCHAR(10),
     @S20    NVARCHAR(10),
     @S21    NVARCHAR(10),
     @Desc    NVARCHAR(300),   ----工作说明
     @Auditor   nvarchar(50)   ----审批人 02.0100 张三
      * @param bizId
     */
    private void callProcess(String bizId){

        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.PersonFileCheckBase);
        StringBuilder sql = new StringBuilder("SELECT * from ")
                .append(tableName).append(" where id ='")
                //.append("' and oneLevelCode='").append(oneLevelCode)
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());

        log.info("入参map={}",map);

        //调用存储过程
        String company = MapUtils.getString(map,"company","");
        String baseOrgCode = MapUtils.getString(map,"baseOrgCode","");
        String posNumber = MapUtils.getString(map,"posNumber","");
        String personNum = MapUtils.getString(map,"personNum","");
        String Report = MapUtils.getString(map,"Report","");
        switch (Report) {
            case "√":
                Report = "yes";
                break;
            case "×":
                Report = "no";
                break;
            case "/":
                Report = "";
                break;
        }

        String contract = MapUtils.getString(map,"contract","");
        switch (contract) {
            case "√":
                contract = "yes";
                break;
            case "×":
                contract = "no";
                break;
            case "/":
                contract = "";
                break;
        }

        String resume = MapUtils.getString(map,"resume","");
        switch (resume) {
            case "√":
                resume = "yes";
                break;
            case "×":
                resume = "no";
                break;
            case "/":
                resume = "";
                break;
        }
        String pic = MapUtils.getString(map,"pic","");
        switch (pic) {
            case "√":
                pic = "yes";
                break;
            case "×":
                pic = "no";
                break;
            case "/":
                pic = "";
                break;
        }
        String certificate = MapUtils.getString(map,"certificate","");
        switch (certificate) {
            case "√":
                certificate = "yes";
                break;
            case "×":
                certificate = "no";
                break;
            case "/":
                certificate = "";
                break;
        }


        String educationBac = MapUtils.getString(map,"educationBac","");
        switch (educationBac) {
            case "√":
                educationBac = "yes";
                break;
            case "×":
                educationBac = "no";
                break;
            case "/":
                educationBac = "";
                break;
        }
        String employmentFile = MapUtils.getString(map,"employmentFile","");
        switch (employmentFile) {
            case "√":
                employmentFile = "yes";
                break;
            case "×":
                employmentFile = "no";
                break;
            case "/":
                employmentFile = "";
                break;
        }
        String laborCost = MapUtils.getString(map,"laborCost","");
        switch (laborCost) {
            case "√":
                laborCost = "yes";
                break;
            case "×":
                laborCost = "no";
                break;
            case "/":
                laborCost = "";
                break;
        }

        String training = MapUtils.getString(map,"training","");
        switch (training) {
            case "√":
                training = "yes";
                break;
            case "×":
                training = "no";
                break;
            case "/":
                training = "";
                break;
        }
        String retirementFile = MapUtils.getString(map,"retirementFile","");
        switch (retirementFile) {
            case "√":
                retirementFile = "yes";
                break;
            case "×":
                retirementFile = "no";
                break;
            case "/":
                retirementFile = "";
                break;
        }

        String specialArchives = MapUtils.getString(map,"specialArchives","");
        switch (specialArchives) {
            case "√":
                specialArchives = "yes";
                break;
            case "×":
                specialArchives = "no";
                break;
            case "/":
                specialArchives = "";
                break;
        }
        String Directory = MapUtils.getString(map,"Directory","");
        switch (Directory) {
            case "√":
                Directory = "yes";
                break;
            case "×":
                Directory = "no";
                break;
            case "/":
                Directory = "";
                break;
        }
        String summary = MapUtils.getString(map,"summary","");
        switch (summary) {
            case "√":
                summary = "yes";
                break;
            case "×":
                summary = "no";
                break;
            case "/":
                Directory = "";
                break;
        }
        String workDesc = MapUtils.getString(map,"workDesc","");
        String auditer = MapUtils.getString(map,"auditer","");




//        Assert.isFalse(StringUtils.isEmpty(company),"{}不能为空","company");
////        Assert.isFalse(firstDept==null ,"{}不能为空","firstDept");
//        Assert.isFalse(StringUtils.isEmpty(baseOrgCode),"{}不能为空","baseOrgCode");
//        Assert.isFalse(StringUtils.isEmpty(posNumber),"{}不能为空","posNumber");
//        Assert.isFalse(StringUtils.isEmpty(personNum),"{}不能为空","personNum");
//        Assert.isFalse(StringUtils.isEmpty(Report),"{}不能为空","Report");
//        Assert.isFalse(StringUtils.isEmpty(contract),"{}不能为空","contract");
//        Assert.isFalse(StringUtils.isEmpty(resume),"{}不能为空","resume");
//        Assert.isFalse(StringUtils.isEmpty(pic),"{}不能为空","pic");
//        Assert.isFalse(StringUtils.isEmpty(certificate),"{}不能为空","certificate");
//        Assert.isFalse(StringUtils.isEmpty(educationBac),"{}不能为空","educationBac");
//        Assert.isFalse(StringUtils.isEmpty(employmentFile),"{}不能为空","employmentFile");
//        Assert.isFalse(StringUtils.isEmpty(laborCost),"{}不能为空","laborCost");
//        Assert.isFalse(StringUtils.isEmpty(training),"{}不能为空","training");
//        Assert.isFalse(StringUtils.isEmpty(retirementFile),"{}不能为空","retirementFile");
//        Assert.isFalse(StringUtils.isEmpty(specialArchives),"{}不能为空","specialArchives");
//        Assert.isFalse(StringUtils.isEmpty(Directory),"{}不能为空","Directory");
//        Assert.isFalse(StringUtils.isEmpty(summary),"{}不能为空","summary");
//        Assert.isFalse(StringUtils.isEmpty(auditer),"{}不能为空","auditer");


        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncHrArchCheck   '%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'",
                company,baseOrgCode,posNumber,personNum,Report,contract,resume,pic,certificate,educationBac,employmentFile,laborCost,training,retirementFile,specialArchives,Directory,summary,workDesc,auditer);

        log.info("\n==========准备调用存储过程:{}",execSql);

        sqlService.execute(CloudSqlService.htEas,execSql);

        log.info("\n=============存储过程执行完成");

    }



    /**
     *  查询审批人,返回  员工号+姓名
     * @param bizObject
     * @return
     */
    private String getFileBaseInfoWorkFlowApproval(BizObjectCreatedModel bizObject) {


        WorkflowInstanceModel instanceModel = getWorkflowInstanceFacade().getByObjectId(bizObject.getId());
        List<WorkItemModel> workItems = getWorkflowInstanceFacade().getWorkItems(instanceModel.getId(), true);
        final String finalActivityCode = "Activity9";
        Optional<WorkItemModel> first = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode)).findFirst();
        String participant = null;
        if (first.isPresent()) {
            WorkItemModel workItemModel = first.get();
            participant = workItemModel.getParticipant();
        }

        if (participant == null) {
            participant = bizObject.getCreater().getId();
        }

        UserModel user = getOrganizationFacade().getUser(participant);


        return new StringBuilder(user.getEmployeeNo()).append("　").append(user.getName()).toString();
    }



    /**
     * 判断是否已存在
     * @return
     */
    private String existsBizObject(Map data){

        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.PersonFileCheckBase);
        String companyNumber = (String) data.get("companyNumber");
        String personNumberHidden = (String) data.get("personNumberHidden");

        StringBuilder sql = new StringBuilder("select id  from ").append(tableName)
                .append(" where companyCode='").append(companyNumber)
                .append("' and personNum='").append(personNumberHidden)
                .append("';");

        Map<String, Object> map = sqlService.getMap(sql.toString());

        return (String) map.get("id");
    }

    /**
     *  转换成  基础表-错失标准 的数据
     * @param map
     * @param auditDate
     * @return
     */
    private Map<String,Object> fileInfoBaseMap(Map<String,Object> map,String auditDate,String auditer){
        Map<String, Object> data = new HashMap<>();


        //关联单选公司
        data.put("company",map.get("company"));
        //公司代碼
        data.put("companyCode",map.get("companyNumber"));
        //公司名称
        data.put("companyName",map.get("companyName"));

        //关联单选基层组织代码
        data.put("baseOrgCode",map.get("baseOrgCode"));
        //基层组织代码
        data.put("baseOrgNumber",map.get("baseOrgNumber"));
        //基层组织
        data.put("baseOrgName",map.get("baseOrg"));

        //关联单选岗
        data.put("posCode",map.get("posCode"));
        //岗代码
        data.put("posNumber",map.get("posNumber"));
        //岗
        data.put("posName",map.get("personName"));

        //关联单选人员代码
        data.put("personnumber",map.get("personnumber"));
        //人员代码
        data.put("personNum",map.get("personNumberHidden"));
        //人员
        data.put("personName",map.get("personName"));

        //人员状态
        data.put("personStatus",map.get("personStatus"));


        //01 报告
        data.put("Report",map.get("Report"));

        //02合同
        data.put("contract",map.get("contract"));
        //03履历
        data.put("resume",map.get("resume"));
        //04照片
        data.put("pic",map.get("pic"));
        //05身份证明
        data.put("certificate",map.get("Identification"));
        //06学历、职称
        data.put("educationBac",map.get("education"));
        //07录用档案
        data.put("employmentFile",map.get("employmentFile"));
        //08人力成本
        data.put("laborCost",map.get("laborCost"));

        //09培训
        data.put("training",map.get("training"));
        //10去职档案
        data.put("retirementFile",map.get("retirementFile"));
        //14 专项档案
        data.put("specialArchives",map.get("specialArchives"));
        //20人事档案目录
        data.put("Directory",map.get("Directory"));
        //20*总结、奖惩等
        data.put("summary",map.get("summary"));
        //工作说明
        data.put("workDesc",map.get("workDesc"));




        //审批时间
        data.put("auditDate",auditDate);
        //审批人
        data.put("auditer",auditer);

        return data;
    }
}

